package org.example;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
/**
 * JWT工具类，用于生成、验证和解析JWT
 */
public class JwtDemo {
    // 秘钥（实际项目应该从配置读取）
    private static final String SECRET = "my-32-character-ultra-secure-secret";
    private static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes());

    // 过期时间1小时
    private static final long EXPIRATION = 3600 * 1000;

    // 生成Token
    public static String createToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY)
                .compact();
    }

    // 验证Token
    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 从Token获取用户名
    public static String getUsername(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public static void main(String[] args) {
        // 测试生成Token
        String token = createToken("testUser");
        System.out.println("生成的Token: " + token);

        // 验证Token
        boolean isValid = validateToken(token);
        System.out.println("Token是否有效: " + isValid);

        // 获取用户名
        String username = getUsername(token);
        System.out.println("从Token获取的用户名: " + username);

        // 测试无效Token
        boolean invalidCheck = validateToken("invalid.token.here");
        System.out.println("无效Token检查: " + invalidCheck);
    }

}